package handler

import (
	"net/http"

	"database/sql"

	"gitee.com/hp-huiw/family-expense-api/internal/dto"
	"gitee.com/hp-huiw/family-expense-api/internal/service"
	"github.com/gin-gonic/gin"
)

type AppErrorReportHandler interface {
	Send(ctx *gin.Context)
}

func NewAppErrorReportHandler(db *sql.DB) AppErrorReportHandler {
	return &appErrorReportHandler{
		appErrorReportService: service.NewAppErrorReportService(db),
	}
}

// Matches /save of http post action.
func (h *appErrorReportHandler) Send(ctx *gin.Context) {
	postedData := dto.AppErrorReportRequest{}

	if err := ctx.ShouldBindJSON(&postedData); err != nil {
		ctx.Error(err)
		return
	}

	c := ctx.Request.Context()
	claims := GetClaims(ctx)

	// If user is authenticated we need to get username.
	if claims != nil {
		postedData.Username = &claims.Username
	}

	if err := h.appErrorReportService.Save(c, &postedData); err != nil {
		ctx.Error(err)
		return
	}

	SendStatusResponse(ctx, http.StatusNoContent)
}

// Container of AppErrorReportHandler functions.
type appErrorReportHandler struct {
	appErrorReportService service.AppErrorReportService
}
